<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>定时器的应用</title>
    <style>
      #box {
        width: 100px;
        height: 100px;
        position: absolute;
        background-color: red;
        left: 0;
      }

      .line {
        position: absolute;
        height: 100%;
        width: 1px;
        left: 800px;
        top: 0;
        background-color: black;
      }
    </style>
  </head>
  <body>
    <button id="btn">按下向右移动</button>
    <br /><br />

    <div id="box"></div>

    <!-- 一条竖线 -->
    <div class="line"></div>

    <script>
      var box = document.getElementById("box");
      var btn = document.getElementById("btn");

      btn.onclick = function () {
        move(box, 800, 10);
      };

      // 封装移动函数
      function move(obj, target, speed) {
        clearInterval(obj.timer);

        var current = parseInt(getStyle(obj, "left"));
        if (current > target) {
          speed = -speed;
        }

        obj.timer = setInterval(function () {
          var oldValue = parseInt(getStyle(obj, "left"));
          var newValue = oldValue + speed;
          if ((newValue > target && speed > 0) || (speed < 0 && newValue < target)) {
            newValue = target;
          }
          box.style.left = newValue + "px";

          if (newValue === 800) {
            clearInterval(obj.timer);
          }
        }, 30);
      }

      function getStyle(obj, name) {
        if (window.getComputedStyle) {
          return getComputedStyle(obj, null)[name];
        } else {
          // IE8方式
          return obj.currentStyle[name];
        }
      }
    </script>
  </body>
</html>
